<template>
  <div class="app-container">
    <!-- 搜索区域 -->
    <el-card class="search-card">
      <el-form :inline="true" :model="searchForm" class="search-form">
        <el-form-item label="中药名称">
          <el-input v-model="searchForm.name" placeholder="请输入中药名称" clearable/>
        </el-form-item>
<!--        <el-form-item label="功效分类">-->
<!--          <el-select v-model="searchForm.category" placeholder="请选择分类" clearable>-->
<!--            <el-option v-for="item in categoryOptions" :key="item.value" :label="item.label" :value="item.value"/>-->
<!--          </el-select>-->
<!--        </el-form-item>-->
<!--        <el-form-item label="性味归经">-->
<!--          <el-select v-model="searchForm.property" placeholder="请选择性味" clearable>-->
<!--            <el-option v-for="item in propertyOptions" :key="item.value" :label="item.label" :value="item.value"/>-->
<!--          </el-select>-->
<!--        </el-form-item>-->
        <el-form-item>
          <el-button type="primary" :icon="Search" @click="handleSearch">搜索</el-button>
          <el-button :icon="Refresh" @click="resetSearch">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 操作按钮区域 -->
    <div class="action-container">
      <el-button type="primary" :icon="Plus" @click="handleAdd">添加中药</el-button>
      <!--      <el-button type="danger" :icon="Delete" :disabled="!selectedItems.length" @click="handleBatchDelete">批量删除-->
      <!--      </el-button>-->
      <el-button type="success" :icon="Upload" @click="handleImport">导入</el-button>
      <el-button type="info" :icon="Download" @click="handleExport">导出</el-button>
    </div>

    <!-- 表格区域 -->
    <el-card>
      <el-table
          v-loading="loading"
          :data="tableData"
          border
          style="width: 100%"
          @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55"/>
        <el-table-column prop="id" label="ID" width="80"/>
        <el-table-column prop="name" label="中药名称" width="150"/>
        <el-table-column prop="pinyin" label="拼音" width="120"/>
        <el-table-column prop="alias" label="别名" width="180"/>
        <el-table-column prop="category" label="功效分类" width="120"/>
        <el-table-column prop="property" label="性味" width="100"/>
        <el-table-column prop="meridian" label="归经" width="150"/>
        <el-table-column prop="efficacy" label="功效" min-width="200" show-overflow-tooltip/>
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="scope">
            <el-button link type="primary" size="small" @click="handleView(scope.row)">查看</el-button>
            <el-button link type="primary" size="small" @click="handleEdit(scope.row)">编辑</el-button>
            <el-button link type="danger" size="small" @click="handleDelete(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
            v-model:current-page="currentPage"
            v-model:page-size="pageSize"
            :page-sizes="[10, 20, 50, 100]"
            layout="total, sizes, prev, pager, next, jumper"
            :total="total"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 添加/编辑对话框 -->
    <el-dialog
        v-model="dialogVisible"
        :title="dialogType === 'add' ? '添加中药' : '编辑中药'"
        width="650px"
        @closed="resetForm"
    >
      <el-form
          ref="formRef"
          :model="formData"
          :rules="formRules"
          label-width="100px"
          label-position="right"
      >
        <el-form-item label="中药名称" prop="name">
          <el-input v-model="formData.name" placeholder="请输入中药名称"/>
        </el-form-item>
        <el-form-item label="拼音" prop="pinyin">
          <el-input v-model="formData.pinyin" placeholder="请输入拼音"/>
        </el-form-item>
        <el-form-item label="别名" prop="alias">
          <el-input v-model="formData.alias" placeholder="请输入别名，多个用逗号分隔"/>
        </el-form-item>
        <el-form-item label="功效分类" prop="category">
          <el-select v-model="formData.category" placeholder="请选择分类" style="width: 100%">
            <el-option v-for="item in categoryOptions" :key="item.value" :label="item.label" :value="item.value"/>
          </el-select>
        </el-form-item>
        <el-form-item label="性味" prop="property">
          <el-select v-model="formData.property" placeholder="请选择性味" style="width: 100%">
            <el-option v-for="item in propertyOptions" :key="item.value" :label="item.label" :value="item.value"/>
          </el-select>
        </el-form-item>
        <el-form-item label="归经" prop="meridian">
          <el-select v-model="formData.meridian" multiple placeholder="请选择归经" style="width: 100%">
            <el-option v-for="item in meridianOptions" :key="item.value" :label="item.label" :value="item.value"/>
          </el-select>
        </el-form-item>
        <el-form-item label="功效" prop="efficacy">
          <el-input v-model="formData.efficacy" type="textarea" rows="3" placeholder="请输入功效"/>
        </el-form-item>
        <el-form-item label="用法用量" prop="usage">
          <el-input v-model="formData.usage" type="textarea" rows="3" placeholder="请输入用法用量"/>
        </el-form-item>
        <el-form-item label="禁忌" prop="contraindications">
          <el-input v-model="formData.contraindications" type="textarea" rows="3" placeholder="请输入禁忌"/>
        </el-form-item>
        <el-form-item label="图片" prop="image">
          <el-upload
              action="#"
              list-type="picture-card"
              :auto-upload="false"
              :limit="1"
              :file-list="fileList"
              :http-request="excelUpload"
              :on-change="handleImageChange"
          >
            <el-icon>
              <Plus/>
            </el-icon>
          </el-upload>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitForm">确定</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 查看详情对话框 -->
    <el-dialog
        v-model="viewDialogVisible"
        title="中药详情"
        width="700px"
    >
      <el-descriptions :column="2" border>
        <el-descriptions-item label="中药名称">{{ detailData.name }}</el-descriptions-item>
        <el-descriptions-item label="拼音">{{ detailData.pinyin }}</el-descriptions-item>
        <el-descriptions-item label="别名">{{ detailData.alias }}</el-descriptions-item>
        <el-descriptions-item label="功效分类">{{ detailData.category }}</el-descriptions-item>
        <el-descriptions-item label="性味">{{ detailData.property }}</el-descriptions-item>
        <el-descriptions-item label="归经">{{ detailData.meridian }}</el-descriptions-item>
        <el-descriptions-item label="功效" :span="2">{{ detailData.efficacy }}</el-descriptions-item>
        <el-descriptions-item label="用法用量" :span="2">{{ detailData.usage }}</el-descriptions-item>
        <el-descriptions-item label="禁忌" :span="2">{{ detailData.contraindications }}</el-descriptions-item>
        <el-descriptions-item label="图片" :span="2">
          <el-image
              v-if="detailData.image"
              :src="detailData.image"
              style="width: 200px; height: 200px"
              :preview-src-list="[detailData.image]"
              fit="cover"
          />
          <span v-else>暂无图片</span>
        </el-descriptions-item>
      </el-descriptions>
    </el-dialog>

    <!-- 导入对话框 -->
    <el-dialog
        v-model="importDialogVisible"
        title="导入中药数据"
        width="500px"
    >
      <el-upload
          class="upload-demo"
          drag
          action="#"
          :auto-upload="false"
          :on-change="handleImportFileChange"
      >
        <el-icon class="el-icon--upload">
          <Upload/>
        </el-icon>
        <div class="el-upload__text">
          拖拽文件到此处，或<em>点击上传</em>
        </div>
        <template #tip>
          <div class="el-upload__tip">
            请上传xlsx或csv格式的文件，
            <el-button link type="primary" @click="downloadTemplate">下载模板</el-button>
          </div>
        </template>
      </el-upload>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="importDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="confirmImport">确定导入</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import {ref, reactive, onMounted} from 'vue'
import {Search, Refresh, Plus, Delete, Upload, Download} from '@element-plus/icons-vue'
import {ElMessage, ElMessageBox} from 'element-plus'
import {
  getHerbList,
  getHerbDetail,
  addHerb,
  updateHerb,
  deleteHerb,
  batchDeleteHerbs,
  getZhongYaoKnowledgeList_API,
  addZhongYaoKnowledgeList_API,
  editZhongYaoKnowledgeList_API,
  delZhongYaoKnowledgeList_API
} from '@/api/knowledge'
import {uoloadFile_API} from "@/api/operation";

// 数据加载状态
const loading = ref(false)

// 表格数据
const tableData = ref([])
const total = ref(0)
const currentPage = ref(1)
const pageSize = ref(10)
const selectedItems = ref([])

// 搜索表单
const searchForm = reactive({
  name: '',
  category: '',
  property: ''
})

// 表单数据
const dialogType = ref('add') // 'add' 或 'edit'
const dialogVisible = ref(false)
const viewDialogVisible = ref(false)
const importDialogVisible = ref(false)
const formRef = ref(null)
const formData = reactive({
  id: '',
  name: '',
  pinyin: '',
  alias: '',
  category: '',
  property: '',
  meridian: [],
  efficacy: '',
  usage: '',
  contraindications: '',
  image: ''
})
const detailData = ref({})
const fileList = ref([])

// 表单验证规则
const formRules = {
  name: [
    {required: true, message: '请输入中药名称', trigger: 'blur'},
    {min: 1, max: 50, message: '长度在 1 到 50 个字符', trigger: 'blur'}
  ],
  // category: [
  //   {required: true, message: '请选择功效分类', trigger: 'change'}
  // ],
  // property: [
  //   {required: true, message: '请选择性味', trigger: 'change'}
  // ]
}

// 功效分类选项
const categoryOptions = [
  {value: '解表药', label: '解表药'},
  {value: '清热药', label: '清热药'},
  {value: '泻下药', label: '泻下药'},
  {value: '祛风湿药', label: '祛风湿药'},
  {value: '化湿药', label: '化湿药'},
  {value: '利水渗湿药', label: '利水渗湿药'},
  {value: '温里药', label: '温里药'},
  {value: '理气药', label: '理气药'},
  {value: '消食药', label: '消食药'},
  {value: '驱虫药', label: '驱虫药'},
  {value: '止血药', label: '止血药'},
  {value: '活血化瘀药', label: '活血化瘀药'},
  {value: '化痰止咳平喘药', label: '化痰止咳平喘药'},
  {value: '安神药', label: '安神药'},
  {value: '平肝息风药', label: '平肝息风药'},
  {value: '补虚药', label: '补虚药'},
  {value: '收涩药', label: '收涩药'},
  {value: '开窍药', label: '开窍药'}
]

// 性味选项
const propertyOptions = [
  {value: '辛温', label: '辛温'},
  {value: '辛凉', label: '辛凉'},
  {value: '苦寒', label: '苦寒'},
  {value: '苦热', label: '苦热'},
  {value: '甘温', label: '甘温'},
  {value: '甘平', label: '甘平'},
  {value: '甘凉', label: '甘凉'},
  {value: '酸温', label: '酸温'},
  {value: '酸平', label: '酸平'},
  {value: '咸寒', label: '咸寒'},
  {value: '咸温', label: '咸温'},
  {value: '淡平', label: '淡平'},
  {value: '淡寒', label: '淡寒'}
]

// 归经选项
const meridianOptions = [
  {value: '肺经', label: '肺经'},
  {value: '大肠经', label: '大肠经'},
  {value: '胃经', label: '胃经'},
  {value: '脾经', label: '脾经'},
  {value: '心经', label: '心经'},
  {value: '小肠经', label: '小肠经'},
  {value: '膀胱经', label: '膀胱经'},
  {value: '肾经', label: '肾经'},
  {value: '心包经', label: '心包经'},
  {value: '三焦经', label: '三焦经'},
  {value: '胆经', label: '胆经'},
  {value: '肝经', label: '肝经'}
]

// 搜索操作
const handleSearch = () => {
  currentPage.value = 1
  fetchData(searchForm.name)
}

// 重置搜索
const resetSearch = () => {
  searchForm.name = ''
  searchForm.category = ''
  searchForm.property = ''
  handleSearch()
}

// 获取中药列表
const fetchData = async (search) => {
  loading.value = true

  const res = await getZhongYaoKnowledgeList_API(search?{search}:undefined)
  console.log('res', res)
  tableData.value = res.data || []
  loading.value = false

}

// 选择变更
const handleSelectionChange = (selection) => {
  selectedItems.value = selection
}

// 查看详情
const handleView = (row) => {
  // 实际应用中应该调用API
  // getHerbDetail(row.id).then(res => {
  //   detailData.value = res.data
  //   viewDialogVisible.value = true
  // })

  // 模拟数据
  detailData.value = {...row}
  viewDialogVisible.value = true
}

// 添加中药
const handleAdd = () => {
  dialogType.value = 'add'
  dialogVisible.value = true
}

// 编辑中药
const handleEdit = (row) => {
  dialogType.value = 'edit'
  // 复制数据，避免双向绑定
  Object.keys(formData).forEach(key => {
    if (key === 'meridian' && typeof row[key] === 'string') {
      formData[key] = row[key].split('、')
    } else {
      formData[key] = row[key]
    }
  })

  // 处理图片
  if (row.image) {
    fileList.value = [{
      name: 'image.jpg',
      url: row.image
    }]
  } else {
    fileList.value = []
  }

  dialogVisible.value = true
}

// 删除中药
const handleDelete = (row) => {
  ElMessageBox.confirm(`确定删除中药 ${row.name} 吗？`, '警告', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    loading.value = true
    // 添加调试日志
    delZhongYaoKnowledgeList_API({herbId:row.herbId}).then(response => {
      console.log('删除成功，响应:', response)
      ElMessage.success('删除成功')
      fetchData()
    }).catch(error => {
      ElMessage.error('删除失败')
    }).finally(() => {
      loading.value = false
    })
  }).catch(() => {
    // 用户取消删除操作
  })
}

// 批量删除中药
// const handleBatchDelete = () => {
//   if (selectedItems.value.length === 0) {
//     ElMessage.warning('请至少选择一条记录')
//     return
//   }
//
//   ElMessageBox.confirm(`确定删除选中的 ${selectedItems.value.length} 条记录吗？`, '警告', {
//     confirmButtonText: '确定',
//     cancelButtonText: '取消',
//     type: 'warning'
//   }).then(() => {
//     loading.value = true
//     const ids = selectedItems.value.map(item => item.id)
//     console.log('批量删除IDs:', ids)
//     batchDeleteHerbs(ids).then(response => {
//       console.log('批量删除成功，响应:', response)
//       ElMessage.success('批量删除成功')
//       fetchData()
//     }).catch(error => {
//       console.error('批量删除失败:', error)
//       ElMessage.error('批量删除失败')
//     }).finally(() => {
//       loading.value = false
//     })
//   }).catch(() => {
//     // 用户取消删除操作
//   })
// }

// 导入
const handleImport = () => {
  importDialogVisible.value = true
}

// 导入文件变更
const handleImportFileChange = (file) => {
  console.log('选择导入文件:', file)
}

// 确认导入
const confirmImport = () => {
  ElMessage.success('导入成功')
  importDialogVisible.value = false
  fetchData()
}

// 下载模板
const downloadTemplate = () => {
  ElMessage.info('下载模板')
}

// 导出
const handleExport = () => {
  ElMessage.success('导出成功')
}
const excelUpload = async (file) => {

}
// 图片变更
const handleImageChange = async (file) => {
  try {
    const formData = new FormData();
    formData.append('file', file.raw);
    let header = {"Content-Type": "multipart/form-data"};
    const res = await uoloadFile_API(formData, header);
    formData.image = res.data
  } catch (error) {
    console.error('上传文件时出错:', error);
  }
};

// 提交表单（添加或编辑）
const submitForm = () => {
  formRef.value.validate((valid) => {
    if (valid) {
      loading.value = true

      // 构建提交数据
      const submitData = {
        ...formData,
        // 确保meridian是字符串
        meridian: Array.isArray(formData.meridian) ? formData.meridian.join('、') : formData.meridian
      }

      console.log('提交数据:', submitData)

      if (dialogType.value === 'edit') {
        editZhongYaoKnowledgeList_API(submitData).then(response => {
          console.log('更新成功，响应:', response)
          ElMessage.success('更新成功')
          dialogVisible.value = false
          fetchData()
        }).catch(error => {
          console.error('更新失败:', error)
          ElMessage.error('更新失败')
        }).finally(() => {
          loading.value = false
        })
      } else {
        addZhongYaoKnowledgeList_API(submitData).then(response => {
          console.log('添加成功，响应:', response)
          ElMessage.success('添加成功')
          dialogVisible.value = false
          fetchData()
        }).catch(error => {
          console.error('添加失败:', error)
          ElMessage.error('添加失败')
        }).finally(() => {
          loading.value = false
        })
      }
    }
  })
}

// 重置表单
const resetForm = () => {
  formRef.value?.resetFields()
  Object.keys(formData).forEach(key => {
    if (key === 'meridian') {
      formData[key] = []
    } else {
      formData[key] = ''
    }
  })
  fileList.value = []
}

// 分页大小变更
const handleSizeChange = (val) => {
  pageSize.value = val
  fetchData()
}

// 页码变更
const handleCurrentChange = (val) => {
  currentPage.value = val
  fetchData()
}

// 页面加载时获取数据
onMounted(() => {
  fetchData()
})
</script>

<style lang="scss" scoped>
.app-container {
  padding: 20px;

  .search-card {
    margin-bottom: 20px;
  }

  .action-container {
    margin-bottom: 20px;
    display: flex;
    justify-content: flex-start;
    gap: 10px;
  }

  .pagination-container {
    margin-top: 20px;
    display: flex;
    justify-content: flex-end;
  }
}
</style> 